package com.itany.shop.service.impl;

import com.itany.shop.dao.UserDao;
import com.itany.shop.entity.User;
import com.itany.shop.exception.*;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.util.MD5Util;
import com.itany.shop.util.ParameterUtil;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/14 13:35
 * Version:1.0-SNAPSHOT
 * Description:
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao = (UserDao) ObjectFactory.getObject("userDao");

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException, ServiceException {
        if(ParameterUtil.isNull(username) || ParameterUtil.isNull(password) || ParameterUtil.isNull(phone) || ParameterUtil.isNull(address)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        // 判断当前用户名是否已经被注册
        try {
            User selectUser = userDao.selectByUsername(username);
            if(selectUser != null){
                throw new UserExistException("该用户已经被注册");
            }
            // 如果用户名可用,则直接添加
            User user = new User(username, MD5Util.md5(password),phone,address);
            userDao.insertUser(user);
        } catch (DataAccessException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }

    }

    @Override
    public User login(String username, String password, String code, String image) throws RequestParameterErrorException, CodeErrorException, UserNotExistException, ServiceException {
        if(ParameterUtil.isNull(username) || ParameterUtil.isNull(password) || ParameterUtil.isNull(code) || ParameterUtil.isNull(image)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        if(!code.equals(image)){
            throw new CodeErrorException("验证码不正确");
        }
        // 登录时需要注意密码的问题
        // 由于注册的时候密码使用了MD5进行加密
        // 因此,在登录的时候,需要将前台获取的密码通过MD5进行加密之后
        // 再去数据库中与数据库里面的密码进行比较
        try {
            User user = userDao.selectByUsernameAndPassword(username,MD5Util.md5(password));
            if(null == user){
                throw new UserNotExistException("用户名或密码错误");
            }
            return user;
        } catch (DataAccessException e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
